<template>
  <CardSwList>
    <a-card>
      <BasicForm :labelWidth="100" @register="registerForm" :actionColOptions="{ span: 8 }" :baseColProps="{ span: 3 }" @submit="handleSubmit" />
    </a-card>
    <div>
      <BasicTable @register="registerTable2" :pagination="pagination"></BasicTable>
    </div>
    <div>
      <!--引用表格-->
      <BasicTable @register="registerTable" :rowSelection="rowSelection">
        <!--插槽:table标题-->
        <template #tableTitle>
          <a-button type="primary" preIcon="ant-design:plus-outlined" @click="handleInit"> 初始化</a-button>
          <a-button type="primary" @click="handleEdit" v-if="!startEdit" :disabled="btnIsDisabled">批量编辑</a-button>
          <a-button type="primary" @click="handleSave" v-if="startEdit">保存</a-button>
          <a-button @click="handleCancel" v-if="startEdit">取消</a-button>
        </template>
        <template #bodyCell="{ column, text, record, index }">
          <template v-if="startEdit && column.editComponent === 'Custom_InputNumber'">
            <a-input-number v-if="startEdit || record.isAdd" :controls="false" :disabled="column.isDisabled" v-model:value="record[column['dataIndex']]" @change="scoreCompute" @focus="handleIndex(index)" />
            <span v-else>
              {{ text }}
            </span>
          </template>
        </template>
        <!--操作栏-->
        <template #action="{ record }">
          <TableAction :actions="getTableAction(record)" />
        </template>
      </BasicTable>
    </div>
  </CardSwList>
</template>

<script lang="ts" name="online-genDataTable" setup>
import { ref, provide, onMounted, reactive, nextTick, watchEffect, computed, unref, watch, defineComponent } from 'vue';
import { CardSwList } from '/@/components/CardList';
import { BasicTable, TableAction } from '/@/components/Table';
import { useListPage } from '/@/hooks/system/useListPage'
import { FormSchema, useForm, BasicForm } from '/@/components/Form';

import { unifyNumber } from '/@/views/zhc/util/numUtils';
import { getMonitoringStatus } from '/@/api/common/api';
import { columns, columns1, searchFormSchema } from './HubTeamResultEvaluate.data';
import { list, list1, updateList, getColumn, getTemplateConfigHeader, deleteOne, init } from './HubTeamResultEvaluate.api';
import { useMessage } from '/@/hooks/web/useMessage'; // 轻提醒
const { createMessage: $message, createConfirm } = useMessage(); // 解构

import { cloneDeep } from 'lodash-es';
const queryParam = reactive<any>({});
//注册table数据
const { tableContext, onExportXls, onImportXls } = useListPage({
  tableProps: {
    api: list,
    columns,
    canResize: false,
    showIndexColumn: true,
    actionColumn: {
      width: 120,
      fixed: 'right'
    },
    immediate: true,
    beforeFetch: (params) => {
      params.orgCode = getFieldsValue().orgCode;
      params.periodCode = getFieldsValue().periodCode;
      return Object.assign(params);
    },
  },
})

const [registerTable, { getForm, reload, getDataSource, getColumns, setColumns, setTableData }, { rowSelection, selectedRows, selectedRowKeys }] = tableContext;

const pagination = ref<any>(false);
//详情表格配置
const { tableContext: tableContext2 } = useListPage({
  tableProps: {
    title: '综合评价明细',
    api: list1,
    columns: columns1,
    canResize: false,
    showIndexColumn: true,
    showActionColumn: false,
    actionColumn: {
      width: 240,
      fixed: 'right'
    },
    immediate: true,
    beforeFetch: (params) => {
      let yearParams = {
        type: 1,
        orgCode: getFieldsValue().orgCode,
        periodCode: getFieldsValue().periodCode?.slice(0, 4)
      };
      return Object.assign(params, yearParams);
    },
  },
})
const [registerTable2, { getForm: getForm1, reload: reload1, getColumns: getColumns1, setColumns: setColumns1, setTableData: setTableData1 }] = tableContext2;

//查询条件表单配置
const [registerForm, { setProps, updateSchema, setFieldsValue, getFieldsValue }] = useForm({
  labelWidth: 120,
  schemas: searchFormSchema,
  actionColOptions: {
    span: 6,
  },
  compact: true,
  showResetButton: true,
  showSubmitButton: true,
  showAdvancedButton: false,     //高级按钮，重置后面的收起、展开
  disabled: false,
});

let currentTableIndex = 0; //记录当前操作的表格数据行
const startEdit = ref(false);
const btnIsDisabled = ref(false);

onMounted(async () => {
  //获取编辑按钮的状态
  await updateSchema([
    {
      field: 'orgCode',
      componentProps: {
        onChange: (e, i) => {
          if (e) {
            initTabColumn(e);
            handleSuccess();
            reload1();
          }
        },
        // atfer request callback
        onOptionsChange: (options) => {
          console.log('get options', options.length, options);
        },
      },
    },
  ]);
  initTabColumn();
});

/**
 * 初始化表头
 */
async function initTabColumn(e?) {
  let params = {
    type: 1,
    orgCode: e ? e : getFieldsValue().orgCode,
    periodCode: getFieldsValue().periodCode?.slice(0, 4)
  };
  getDynamicData(params)
  getTableColumn(params);
}

/**
 * 初始化事件
 */
async function handleInit() {
  $message.info('初始化');
  let params = {
    orgCode: getFieldsValue().orgCode,
    periodCode: getFieldsValue().periodCode,
  };
  await init(params);
  handleSuccess();
}

// 获取详情动态表头
function getTableColumn(params) {
  let newColumn: any = cloneDeep(columns1);
  getTemplateConfigHeader(params).then((res) => {
    res.forEach((item) => {
      let temp = {
        title: item.headName,
        dataIndex: item.headCode,
        width: 180,
        align: 'center',
      };
      newColumn.splice(newColumn.length, 0, {
        ...temp,
      });
    });
    nextTick(() => {
      setColumns1(newColumn);
    });
  });
};

/**
 * 动态表头配置
 * @param params
 */
function getDynamicData(params) {
  let newColumn: any = cloneDeep(columns);
  getColumn(params).then((res) => {
    res.forEach((r) => {
      let temp = {
        title: r.headName,
      };
      //多级表头处理
      let childList = r.children;
      if (childList) {
        //有子列表情况
        let newChildList: any = [];
        childList.forEach((r1) => {
          let childTemp: any = {
            title: r1.headName,
            dataIndex: r1.headCode,
            width: 260,
            align: 'center',
            editComponent: 'Input',
          };
          // if (r1.headName == '评分') {
          //   childTemp.required = true;
          // }
          if (r1.headName == '评分' || r1.headName == '权重') {
            childTemp.editComponent = 'Custom_InputNumber';
            childTemp.width = 120;
          }
          if (r1.headName == '权重') {
            childTemp.title = '权重（%）';
            childTemp.isDisabled = true;
          }
          if (r1.headCode.indexOf('weight') != -1) {
            childTemp.defaultWeight = r.value;
          }
          newChildList.splice(newChildList.length, 0, { ...childTemp });
        });
        temp['children'] = newChildList;
      }

      newColumn.splice(newColumn.length - 2, 0, {
        ...temp,
        checkDetail: r.checkDetail, //判断是否能打开详情 boolean
        scopedSlots: { customRender: r.headCode },
      });
    });
    // newColumn[newColumn.length - 1]['fixed'] = 'right';
    //重设表头
    setColumns(newColumn);
  });
};

// 计算分数
const scoreCompute = () => {
  console.log('1111111111');
  let TableData = getDataSource();
  let currentRecord = TableData[currentTableIndex];
  currentRecord.finalScore = 0;
  // 规定10
  for (let i = 1; i <= 10; i++) {
    if (currentRecord[`score${i}`] && currentRecord[`weight${i}`]) {
      console.log('计算currentRecord', currentRecord);
      currentRecord.finalScore += (currentRecord[`score${i}`] / 100) * currentRecord[`weight${i}`];
    }
  }
  currentRecord.finalScore = unifyNumber(currentRecord.finalScore);
};

const handleIndex = (index) => {
  currentTableIndex = index;
};

/**
 * 取消事件
 */
function handleCancel() {
  startEdit.value = false;
  reload();
}

/**
 * 批量保存事件
 */
function handleSave() {
  let dataSource = getDataSource();
  let flagMsg: any = null;
  // dataSource.forEach((item) => {
  //   if (!item.psnName) {
  //     flagMsg = '姓名不能为空';
  //   } else if (!item.keyContent) {
  //     flagMsg = '重点工作内容不能为空';
  //   } else if (!item.finalScore) {
  //     flagMsg = '评分不能为空';
  //     return;
  //   }
  // });
  if (flagMsg) {
    $message.warn(flagMsg);
    return;
  }
  const saveData = {
    datas: dataSource,
    orgCode: getFieldsValue().orgCode,
  };
  updateList(saveData).then((res) => {
    startEdit.value = false;
    reload();
  });
}

const getBtnStatus = () => {
  getMonitoringStatus({
    orgCode: getForm().getFieldsValue().orgCode,
    periodCode: getForm().getFieldsValue().periodCode,
  }).then((res) => {
    btnIsDisabled.value = res.data == '2';
  });
};

/**
 * 新增事件
 */
function handleAdd() {
}
/**
 * 编辑事件
 */
function handleEdit(record: Recordable) {
  startEdit.value = true;
}
/**
 * 删除事件
 */
async function handleDelete(record) {
  await deleteOne({ id: record.id });
  (selectedRowKeys.value = []) && reload();
}
/**
 * 成功回调
 */
function handleSuccess() {
  (selectedRowKeys.value = []) && reload();
}

/**
 * 提交事件
 */
function handleSubmit() {
  let formData = getFieldsValue();
  let params = Object.assign({}, formData);
  console.log('表单数据', params);
  reload({ searchInfo: params });
}

/**
 * 表格操作栏
 */
function getTableAction(record) {
  return [
    // {
    //   label: '编辑',
    //   onClick: handleEdit.bind(null, record)
    // },
    {
      label: '删除',
      color: 'error',
      popConfirm: {
        title: '是否确认删除',
        placement: 'left',
        confirm: handleDelete.bind(null, record),
      }
    }
  ]
}
</script>

<style lang="less" scoped>
:deep(.ant-picker),
:deep(.ant-input-number) {
  width: 100%;
}
</style>